package com.example.iot.actors.app;

import com.example.iot.actors.*;
import com.example.iot.actors.service.ContextAwareActor;
import com.example.iot.actors.service.ContextBasedCreator;
import com.example.iot.actors.service.DefaultActorServiceImpl;
import com.example.iot.entity.RuleChain;
import com.example.iot.entity.id.EntityId;
import com.example.iot.entity.id.EntityType;
import com.example.iot.entity.id.RuleChainId;
import com.example.iot.entity.id.AppId;
import com.example.iot.msg.*;
import com.example.iot.ruleChain.RuleChainActor;
import lombok.extern.slf4j.Slf4j;

/**
 * Actor系统的起始Actor，整个Actor系统的入口
 * @author Chenxiangpeng
 */

@Slf4j
public class AppActor extends ContextAwareActor {

    private boolean ruleChainsInitialized;

    private AppActor(ActorSystemContext systemContext) {
        super(systemContext);
    }

    @Override
    protected boolean doProcess(TbActorMsg msg) {
        if (!ruleChainsInitialized) {
            ruleChainsInitialized = true;
            if (msg.getMsgType() != MsgType.APP_INIT_MSG) {
                log.warn("Rule Chains initialized by unexpected message: {}", msg);
            }
        }
        switch (msg.getMsgType()) {
            case APP_INIT_MSG:
                break;
            case PARTITION_CHANGE_MSG:
                ctx.broadcastToChildren(msg);
                break;
            case COMPONENT_LIFE_CYCLE_MSG:
                // 组件生命周期，包含创建，更新，停止等
                onComponentLifecycleMsg((ComponentLifecycleMsg) msg);
                break;
            case QUEUE_TO_RULE_ENGINE_MSG:
                // 消息来源为消息队列，将消息发送至规则引擎Actor
                QueueToRuleEngineMsg msg1 = (QueueToRuleEngineMsg) msg;
                RuleChainId ruleChainId = msg1.getTbMsg().getRuleChainId();
                RuleChain ruleChain = systemContext.getRuleChainService().findRuleChainById(ruleChainId);
                TbActorRef ruleChainActor = ctx.getOrCreateChildActor(new TbEntityActorId(ruleChainId),
                        () -> DefaultActorServiceImpl.TENANT_DISPATCHER_NAME,
                        // todo 需要查询创建的规则链对象
                        () -> new RuleChainActor.ActorCreator(systemContext, ruleChain));
                ruleChainActor.tell(msg);
                // onQueueToRuleEngineMsg((QueueToRuleEngineMsg) msg);
                break;
            /*case TRANSPORT_TO_DEVICE_ACTOR_MSG:
                onToDeviceActorMsg((TenantAwareMsg) msg, false);
                break;*/
            case DEVICE_ATTRIBUTES_UPDATE_TO_DEVICE_ACTOR_MSG:
            case DEVICE_CREDENTIALS_UPDATE_TO_DEVICE_ACTOR_MSG:
            case DEVICE_NAME_OR_TYPE_UPDATE_TO_DEVICE_ACTOR_MSG:
            case DEVICE_RPC_REQUEST_TO_DEVICE_ACTOR_MSG:
            /*case SERVER_RPC_RESPONSE_TO_DEVICE_ACTOR_MSG:
                onToDeviceActorMsg((TenantAwareMsg) msg, true);
                break;*/
            default:
                return false;
        }
        return true;
    }

    private void onComponentLifecycleMsg(ComponentLifecycleMsg msg) {
        EntityId entityId = msg.getEntityId();
        RuleChain ruleChain = systemContext.getRuleChainService().
                findRuleChainById(new RuleChainId(msg.getEntityId().getId()));
        if (entityId.getEntityType() == EntityType.RULE_CHAIN) {
            TbActorRef target = ctx.getOrCreateChildActor(new TbEntityActorId(entityId),
                    () -> DefaultActorServiceImpl.RULE_DISPATCHER_NAME,
                    () -> new RuleChainActor.ActorCreator(systemContext, ruleChain));
            target.tellWithHighPriority(msg);
        }
    }

    /*private void initTenantActors() {
        log.info("Starting main system actor.");
        try {
            // This Service may be started for specific tenant only.
            Optional<TenantId> isolatedTenantId = systemContext.getServiceInfoProvider().getIsolatedTenant();
            if (isolatedTenantId.isPresent()) {
                Tenant tenant = systemContext.getTenantService().findTenantById(isolatedTenantId.get());
                if (tenant != null) {
                    log.debug("[{}] Creating tenant actor", tenant.getId());
                    getOrCreateTenantActor(tenant.getId());
                    log.debug("Tenant actor created.");
                } else {
                    log.error("[{}] Tenant with such ID does not exist", isolatedTenantId.get());
                }
            } else if (systemContext.isTenantComponentsInitEnabled()) {
                PageDataIterable<Tenant> tenantIterator = new PageDataIterable<>(tenantService::findTenants, ENTITY_PACK_LIMIT);
                boolean isRuleEngine = systemContext.getServiceInfoProvider().isService(ServiceType.TB_RULE_ENGINE);
                boolean isCore = systemContext.getServiceInfoProvider().isService(ServiceType.TB_CORE);
                for (Tenant tenant : tenantIterator) {
                    TenantProfile tenantProfile = tenantProfileCache.get(tenant.getTenantProfileId());
                    if (isCore || (isRuleEngine && !tenantProfile.isIsolatedTbRuleEngine())) {
                        log.debug("[{}] Creating tenant actor", tenant.getId());
                        getOrCreateTenantActor(tenant.getId());
                        log.debug("[{}] Tenant actor created.", tenant.getId());
                    }
                }
            }
            log.info("Main system actor started.");
        } catch (Exception e) {
            log.warn("Unknown failure", e);
        }
    }*/

    /*private void onQueueToRuleEngineMsg(QueueToRuleEngineMsg msg) {
        if (TenantId.SYS_TENANT_ID.equals(msg.getTenantId())) {
            msg.getTbMsg().getCallback().onFailure(new RuleEngineException("Message has system tenant id!"));
        } else {
            if (!deletedTenants.contains(msg.getTenantId())) {
                getOrCreateTenantActor(msg.getTenantId()).tell(msg);
            } else {
                msg.getTbMsg().getCallback().onSuccess();
            }
        }
    }

    private void onComponentLifecycleMsg(ComponentLifecycleMsg msg) {
        TbActorRef target = null;
        if (TenantId.SYS_TENANT_ID.equals(msg.getTenantId())) {
            if (!EntityType.TENANT_PROFILE.equals(msg.getEntityId().getEntityType())) {
                log.warn("Message has system tenant id: {}", msg);
            }
        } else {
            if (EntityType.TENANT.equals(msg.getEntityId().getEntityType())) {
                TenantId tenantId = new TenantId(msg.getEntityId().getId());
                if (msg.getEvent() == ComponentLifecycleEvent.DELETED) {
                    log.info("[{}] Handling tenant deleted notification: {}", msg.getTenantId(), msg);
                    deletedTenants.add(tenantId);
                    ctx.stop(new TbEntityActorId(tenantId));
                } else {
                    target = getOrCreateTenantActor(msg.getTenantId());
                }
            } else {
                target = getOrCreateTenantActor(msg.getTenantId());
            }
        }
        if (target != null) {
            target.tellWithHighPriority(msg);
        } else {
            log.debug("[{}] Invalid component lifecycle msg: {}", msg.getTenantId(), msg);
        }
    }

    private void onToDeviceActorMsg(TenantAwareMsg msg, boolean priority) {
        if (!deletedTenants.contains(msg.getTenantId())) {
            TbActorRef tenantActor = getOrCreateTenantActor(msg.getTenantId());
            if (priority) {
                tenantActor.tellWithHighPriority(msg);
            } else {
                tenantActor.tell(msg);
            }
        } else {
            if (msg instanceof TransportToDeviceActorMsgWrapper) {
                ((TransportToDeviceActorMsgWrapper) msg).getCallback().onSuccess();
            }
        }
    }*/

    /*private TbActorRef getOrCreateTenantActor(TenantId tenantId) {
        return ctx.getOrCreateChildActor(new TbEntityActorId(tenantId),
                () -> DefaultActorService.TENANT_DISPATCHER_NAME,
                () -> new TenantActor.ActorCreator(systemContext, tenantId));
    }*/

    public static class ActorCreator extends ContextBasedCreator {

        public ActorCreator(ActorSystemContext context) {
            super(context);
        }

        @Override
        public TbActorId createActorId() {
            return new TbEntityActorId(AppId.SYS_TENANT_ID);
        }

        @Override
        public TbActor createActor() {
            return new AppActor(context);
        }
    }

}
